import { ElMessage } from 'element-plus'
import axios from 'axios'

const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000,
  withCredentials: true,
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {

    return config
  },
  (error) => {
    ElMessage.error('请求配置错误')
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code !== 200) {
      ElMessage.error(res.message || '请求失败')
      return Promise.reject(new Error(res.message || '请求失败'))
    }
    return res.data
  },
  async (error) => {
    let message = '请求错误'
    if (error.response) {
      const status = error.response.status
      switch (status) {
        case 400: message = '请求参数错误'; break
        case 401: message = '未授权，请登录'; break
        case 403: message = '没有权限'; break
        case 404: message = '请求地址不存在'; break
        case 500: message = '服务器错误'; break
        default: message = `连接错误(${status})`
      }
    } else if (error.message.includes('timeout')) {
      message = '请求超时，请稍后重试'
    } else if (error.message.includes('Network Error')) {
      message = '网络错误，请检查网络连接'
    }

    ElMessage.error(message)
    return Promise.reject(error)
  }
)

export const http = {
  get(url, params) {
    return service.get(url, { params })
  },
  post(url, data) {
    return service.post(url, data)
  },
  put(url, data) {
    return service.put(url, data)
  },
  delete(url, params) {
    return service.delete(url, { params })
  }
}

export default service
